package com.example.bishop.musicplayer_1;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.renderscript.Sampler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    public String str1,str2;
    private Button mBtnBottom;
    private LocalMusicBean musicBean;
    ImageView playIv,iconTv;
    TextView singerTv,songTv;
    RecyclerView musicRv;
    DatabaseHelper databaseHelper;
    SQLiteDatabase database;

/*  弃用  //活动广播动作key
    public static final String UPDATE_ACTION = "com.example.bishop.action.UPDATE_ACTION"; // 更新动作
    public static final String CTL_ACTION = "com.example.bishop.action.CTL_ACTION"; // 控制动作
    public static final String MUSIC_CURRENT = "com.example.bishop.action.MUSIC_CURRENT"; // 当前音乐改变动作
    public static final String MUSIC_DURATION = "com.example.bishop.action.MUSIC_DURATION"; // 音乐时长改变动作
    */


    //数据源
    List<LocalMusicBean> mDatas;
    //定义key用于传递对象
   // public static final String mediaPlayerkey="MEDIA_PLAYER_KEY";
    public static final String mDatakey="MDATA_KEY";
    public static final String CurrentPositionkey="currentPosition";
    private MusicAdapter adapter;
    private int position;
    //记录当前正在播放的音乐的位置
    int currentPlayPosition = -1;
    //记录暂停音乐时进度条的位置
    int currentPausePositionInSong = 0;
    MediaPlayer mediaPlayer;


    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions(MainActivity.this);//申请存储权限
        //创建数据库
        databaseHelper =new DatabaseHelper(this,"songs",null,1);
        database=databaseHelper.getWritableDatabase();

        mBtnBottom = findViewById(R.id.btn_bottom);
        mBtnBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentPlayPosition!=-1) {
                        Intent intent = new Intent(MainActivity.this, Button_Bottom.class);
                       // intent.putExtra("singer", str1);
                        //intent.putExtra("song", str2);

                    /* 旧版数据传递，用数据库代替
                        intent.putExtra("positionkey", currentPlayPosition);//列表的第几个
                        System.out.println(currentPlayPosition);
                        intent.putExtra(CurrentPositionkey, mediaPlayer.getCurrentPosition());//读取当前播放的位置点
                        System.out.println(mediaPlayer.getCurrentPosition());
                    */
                        intent.putExtra("mData_key", (Serializable) mDatas);
                        //写入数据库
                        insertDatabase(currentPlayPosition,mediaPlayer.getCurrentPosition());
                        //searchDatabase();
                        //蠢办法，传递mDatas，点击的数据，播放位置，到下一个界面创建新的mediaplay
                        pauseMusic();
                        //初步完成向第二界面传递歌曲列表。上一曲，下一曲控制没写
                        MainActivity.this.startActivityForResult(intent, 2580);
                    }
                else Toast.makeText(MainActivity.this,"请选择歌曲",Toast.LENGTH_SHORT).show();
                }
        });
        inteView();
        mediaPlayer = new MediaPlayer();
        mDatas = new ArrayList<>();
        //创建适配器对象
        adapter = new MusicAdapter(this, mDatas);
        musicRv.setAdapter(adapter);
        //设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        musicRv.setLayoutManager(layoutManager);

        //加载本地数据源
        loadLocalMusicData();
        //设置每一项的点击事件
        setEventListener();
    }

    private void setEventListener() {//设置每一项的点击事件
        adapter.setOnItemClickListener(new MusicAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                currentPlayPosition = position;
                musicBean = mDatas.get(position);
                //设置底部显示的歌手名和歌曲名
                singerTv.setText(musicBean.getSinger());
                str1=musicBean.getSinger();
                songTv.setText(musicBean.getSong());
                str2=musicBean.getSong();
                stopMusic();
                //重置多媒体播放器

                mediaPlayer.reset();

                //设置新的播放路径

                try {
                    mediaPlayer.setDataSource(musicBean.getPath());
                    System.out.println(musicBean.getPath());

                    playMusic();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                playMusic();

                //product1.setPlayer(mediaPlayer);
            }
        });
    }
    /*点击播放按钮播放音乐，或点击暂停按钮继续播放音乐
    * 有两个情况：
    * 1.从暂停到播放
    * 2.从停止到播放
    * */
    private void playMusic() {//播放音乐的函数
        if (mediaPlayer!=null&&!mediaPlayer.
                isPlaying()) {
            if (currentPausePositionInSong == 0) {//从头开始播放
                try {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{//从暂停处继续播放
                mediaPlayer.seekTo(currentPausePositionInSong);
                mediaPlayer.start();

            }
            playIv.setBackgroundResource(0);
            playIv.setImageResource(R.drawable.play1);
        }
    }
    private void playMusic2(){
        mediaPlayer.seekTo(currentPausePositionInSong);
        mediaPlayer.start();
        playIv.setBackgroundResource(0);
        playIv.setImageResource(R.drawable.play1);
    }

    private void stopMusic() {//停止音乐
        if (mediaPlayer !=null) {
            currentPausePositionInSong = 0;
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            playIv.setImageResource(R.drawable.pause1);
        }
    }

    private void pauseMusic() {//暂停音乐
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
            currentPausePositionInSong = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            playIv.setImageResource(R.drawable.pause1);
        }
    }
    //设置播放器地址
    private void setMediaPlay(int position,int currition) {
        musicBean = mDatas.get(position);
       // stopMusic();
        currentPausePositionInSong=currition;
        mediaPlayer.reset();
        try {
            //mediaPlayer.prepare();
            mediaPlayer.setDataSource(musicBean.getPath());
            // currentPausePositionInSong=0;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void loadLocalMusicData() {
        //加载本地存储当中的mp3文件到集合当中
        //获取contentResolver对象
        ContentResolver resolver = getContentResolver();
        //获取本地音乐存储uri地址
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        //查询地址
        Cursor cursor = resolver.query(uri, null, null, null);

        //遍历cursor
        int id = 0;//给每首歌加id
        while (cursor.moveToNext()) {
            String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            String sid = String.valueOf(id);
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
            String time = sdf.format(duration);
            //将一行当中的数据封装到对象中
            if(duration>30000)//选择时长大于30s的歌曲
            {  id++;
                LocalMusicBean bean = new LocalMusicBean(sid, song, singer, album, time, path);
                mDatas.add(bean);

            }

        }
        //数据源变化，提示适配器更新
        adapter.notifyDataSetChanged();

    }

    private void inteView() {
        //初始化控件的函数
        iconTv = findViewById(R.id.music_BottomIcon);
        playIv = findViewById(R.id.iv_bottom_start);
        singerTv = findViewById(R.id.music_singer);
        songTv = findViewById(R.id.music_name);
        musicRv = findViewById(R.id.music_rv);
        playIv.setOnClickListener(this);
        songTv.setSelected(true);
        singerTv.setSelected(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_bottom_start:
                if (currentPlayPosition == -1) {
                    //没有选中要播放的音乐
                    Toast.makeText(this,"请选择音乐",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mediaPlayer.isPlaying()) {
                    //播放状态下需要暂停
                    pauseMusic();
                }else{
                    //没有播放音乐需要播放
                    playMusic();
                }
            break;
        }
    }

    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //在onCreate()方法中调用该方法即可
  /*  音乐播放服务 */
/*
public class MusicReciver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(MUSIC_CURRENT)) {//当前音乐改变动作
            // currentTime代表当前播放的时间
            currentPlayPosition = intent.getIntExtra("currentTime", -1);
            musicDuration.setText(MediaUtil.formatTime(currentPlayPosition));
        } 
        else if (action.equals(MUSIC_DURATION)) {//音乐时长改变动作
            duration = intent.getIntExtra("duration", -1);
        } 
        else if (action.equals(UPDATE_ACTION)) {//更新动作
            // 获取Intent中的current消息，current代表当前正在播放的歌曲
            listPosition = intent.getIntExtra("current", -1);
            if (listPosition >= 0) {
                musicTitle.setText(mp3Infos.get(listPosition).getTitle());
            }
        }
    }
}
*/
//重写返回方法，调用
/*
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println(requestCode + " " + resultCode + " " + data + " ");
        switch (requestCode) {
            case 2580:
                if (resultCode == RESULT_OK) {
                    position = data.getIntExtra("positionkey", -1);
                    currentPausePositionInSong = data.getIntExtra(CurrentPositionkey, 0);
                    System.out.println(currentPausePositionInSong + " " + position);
                    try {

                        mediaPlayer.seekTo(currentPausePositionInSong);
                        mediaPlayer.start();

                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       // resultCode=1008611;
        searchDatabase();
        //setMediaPlay(position,currentPausePositionInSong);
        System.out.println(position+" hhh"+currentPausePositionInSong);
        playMusic();
       // playMusic2();


    }
//插入数据库
    public void insertDatabase(int p,int c){
        ContentValues values=new ContentValues();
        values.put("position",p);
        values.put("currition",c);
        database.insert("song_info",null,values);

    }
    //查询数据库，读到最后的位置
    public void searchDatabase(){
        Cursor cursor=database.query("song_info",new String[]{"position","currition"},null,null,null,null,null);
        if (cursor.moveToLast()){
            this.position=cursor.getInt(cursor.getColumnIndex("position"));
            this.currentPausePositionInSong=cursor.getInt(cursor.getColumnIndex("currition"));
       // System.out.println(a +" "+b);}
        }
    }
}